var areaData = address;
var $form;
var form;
var $;
layui.config({
	base : "../../js/"
}).use(['form','layer','upload','laydate'],function(){
	form = layui.form();
	var layer = parent.layer === undefined ? layui.layer : parent.layer;
		$ = layui.jquery;
		$form = $('form');
		laydate = layui.laydate;
        loadProvince(); //加载省信息
	
    layui.upload({
    	elem: '.userFaceBtn', //绑定元素
    	url : $.httpRootPath() + "/api/web/manager/picture",
  		type: 'images',
         success: function(res){
         	if(res.code != "00"){
         		layer.msg("服务器异常，请稍候再试");
         	}else{
         		layer.msg("修改成功");
         		$("#userFace").attr("src",res.data.picture);
         	}
  		},
         error: function(){
         	 console.log("失败"); 
    	}
    });
    var index = layer.load(1, {
		shade: [0.1, '#fff']
	});
	var data ={}
    getUser(data,function(){
    	layer.close(index);
    });

    //添加验证规则
    form.verify({
        oldPwd : function(value, item){
            if(value == "123456"){
                return "密码错误，请重新输入！";
            }
        },
        newPwd : function(value, item){
            if(value.length < 3){
                return "密码长度不能小于3位";
            }
        },
        confirmPwd : function(value, item){
            if(!new RegExp($("#oldPwd").val()).test(value)){
                return "两次输入密码不一致，请重新输入！";
            }
        }
    })
	function fillData(userInfo){
	 
	 	$(".account").val(userInfo.account); //用户名
	   	$(".name").val(userInfo.name); //出生年月
        $(".userSex input[value="+userInfo.sex+"]").attr("checked","checked"); //性别
        $(".mobile").val(userInfo.mobile); //
        $(".remark").val(userInfo.remark); //手机号
        $(".email").val(userInfo.email); //手机号
        if(userInfo.picture != ""){
        	$("#userFace").attr("src",userInfo.picture);
        }
        form.render();
	}


    //判断是否修改过头像，如果修改过则显示修改后的头像，否则显示默认头像
    if(window.sessionStorage.getItem('userFace')){
    	$("#userFace").attr("src",window.sessionStorage.getItem('userFace'));
    }else{
    	$("#userFace").attr("src","../../images/face.jpg");
    }

    //提交个人资料
    form.on("submit(changeUser)",function(data){
    	var index = layer.msg('提交中，请稍候',{icon: 16,time:false,shade:0.8});

        var data = {
            'name' : $(".name").val(),
            'remark' : $(".remark").val(),
            'mobile' : $(".mobile").val(),
            'email' : $(".email").val()
        };
   		updateInfo(data,function(){
   	    	layer.close(index);
  		 })
  		 return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    })

    //修改密码
    form.on("submit(changePwd)",function(data){
    	var index = layer.msg('提交中，请稍候',{icon: 16,time:false,shade:0.8});
    	var data  = {
    		'oldPwd':$(".oldPwd").val(),
    		'newPwd':$(".newPwd").val()
    	}
    	updatePwd(data,function(){
    		layer.confirm("密码更新成功,请重新登录", function(index){
  				location.href = '/signin.html'
			});
    		layer.close(index);
            $(".pwd").val('');
    	})
    	return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    })
    
    function getUser(data,callback) {
	$.ajax({
		url: $.httpRootPath() + "/api/web/manager/self",
		type: "get",
		dataType: "json",
		data: data,
		success: function(data) {
			if(data.code == "00") {
				fillData(data.data);
			} else {
				layer.msg(data.msg);
				return;
			}
		},
		error: function() {
			layer.msg("加载失败");
		},
		complete: function() {
			callback();
		}
	})

}

})

//加载省数据
function loadProvince() {
    var proHtml = '';
    for (var i = 0; i < areaData.length; i++) {
        proHtml += '<option value="' + areaData[i].provinceCode + '_' + areaData[i].mallCityList.length + '_' + i + '">' + areaData[i].provinceName + '</option>';
    }
    //初始化省数据
    $form.find('select[name=province]').append(proHtml);
    form.render();
    form.on('select(province)', function(data) {
        $form.find('select[name=area]').html('<option value="">请选择县/区</option>');
        var value = data.value;
        var d = value.split('_');
        var code = d[0];
        var count = d[1];
        var index = d[2];
        if (count > 0) {
            loadCity(areaData[index].mallCityList);
        } else {
            $form.find('select[name=city]').attr("disabled","disabled");
        }
    });
}
//加载市数据
function loadCity(citys) {
    var cityHtml = '<option value="">请选择市</option>';
    for (var i = 0; i < citys.length; i++) {
        cityHtml += '<option value="' + citys[i].cityCode + '_' + citys[i].mallAreaList.length + '_' + i + '">' + citys[i].cityName + '</option>';
    }
    $form.find('select[name=city]').html(cityHtml).removeAttr("disabled");
    form.render();
    form.on('select(city)', function(data) {
        var value = data.value;
        var d = value.split('_');
        var code = d[0];
        var count = d[1];
        var index = d[2];
        if (count > 0) {
            loadArea(citys[index].mallAreaList);
        } else {
            $form.find('select[name=area]').attr("disabled","disabled");
        }
    });
}
//加载县/区数据
function loadArea(areas) {
    var areaHtml = '<option value="">请选择县/区</option>';
    for (var i = 0; i < areas.length; i++) {
        areaHtml += '<option value="' + areas[i].areaCode + '">' + areas[i].areaName + '</option>';
    }
    $form.find('select[name=area]').html(areaHtml).removeAttr("disabled");
    form.render();
    form.on('select(area)', function(data) {});
}

function updateInfo(data, callback) {
	$.ajax({
		url: $.httpRootPath() + '/api/web/manager/update',
		type: 'PUT',
		dataType: 'json',
		data: data,
		timeout: 15000,
		cache: false,
		success: function(r) {
			if(r.code == "00") {
				layer.msg("更新成功！");
			} else {
			layer.msg(r.msg);
			}
		},
		error: function(e) {
			layer.msg("系统错误！");
		},
		complete: function() {
			callback();
		}
	});
	}

function updatePwd(data, callback) {
	data._method='PUT';
	$.ajax({
		url: $.httpRootPath() + '/api/web/manager/modify-pwd',
		type: 'POST',
		dataType: 'json',
		data: data,
		timeout: 15000,
		cache: false,
		success: function(r) {
			if(r.code == "00") {
				layer.msg("更新成功！");
			} else {
				layer.msg(r.msg);
			}
		},
		error: function(e) {
			layer.msg("系统错误！");
		},
		complete: function() {
			callback();
		}
	});
	}
	function showNotice(result){
		layer.open({
	        type: 1,
	        title: "系统公告",
	        closeBtn: false,
	        area: '310px',
	        shade: 0.8,
	        id: 'LAY_layuipro',
	        btn: ['火速围观'],
	        moveType: 1,
	        content: '<div style="padding:15px 20px; text-align:justify; line-height: 22px; text-indent:2em;border-bottom:1px solid #e2e2e2;">'+result+'</div>',
	        success: function(layero){
				var btn = layero.find('.layui-layer-btn');
				btn.css('text-align', 'center');
				btn.on("click",function(){
					window.sessionStorage.setItem("showNotice","true");
				})
				if($(window).width() > 432){  //如果页面宽度不足以显示顶部“系统公告”按钮，则不提示
					btn.on("click",function(){
						layer.tips('系统公告躲在了这里', '#showNotice', {
							tips: 3
						});
					})
				}
	        }
	    });
	}